package nkr1pt.popkorn.interact;

import com.google.inject.Inject;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import nkr1pt.popkorn.download.DownloadCandidate;
import nkr1pt.popkorn.download.DownloadCandidateItem;
import nkr1pt.popkorn.download.DownloadCandidateState;
import nkr1pt.popkorn.download.DownloadManager;
import nkr1pt.popkorn.schedule.DownloadScheduler;


/**
 *
 * @author Kristof Vanhaeren
 */
public class PopkornStatusBuilder {

    private DownloadScheduler downloadScheduler;

    private CopyOnWriteArrayList<DownloadCandidate> downloadCandidates;


    @Inject
    public PopkornStatusBuilder(DownloadManager downloadManager, DownloadScheduler downloadScheduler) {
        this.downloadScheduler = downloadScheduler;
        downloadCandidates = downloadManager.getDownloadCandidates();
    }

    public PopkornStatus buildStatus() {
        PopkornStatus status = new PopkornStatus();
        status.setSchedulerMode(downloadScheduler.getSchedulerMode());
        status.setTotalDownloads(downloadCandidates.size());
        for (DownloadCandidate downloadCandidate : downloadCandidates) {
            switch (downloadCandidate.getState()) {
                case COMPLETE:
                    status.getCompletedDownloads().add(downloadCandidate);
                    break;
                case FAILED:
                    status.getFailedDownloads().add(downloadCandidate);
                    break;
                case INPROGRESS:
                    int total = downloadCandidate.getItems().size();
                    int done = 0;
                    for (DownloadCandidateItem item : downloadCandidate.getItems()) {
                        if (item.getState().equals(DownloadCandidateState.COMPLETE)) {
                            done++;
                        }
                    }
                    status.getBusyDownloads().put(downloadCandidate, done/total*100);
                    break;
                case WAITING:
                    status.getWaitingDownloads().add(downloadCandidate);
                    break;
                case EXTRACTING:
                    status.getExtractingDownloads().add(downloadCandidate);
                    break;
                case EXTRACTED:
                    status.getExtractedDownloads().add(downloadCandidate);
                    break;
            }
        }

        return status;
    }

}